require('es6-promise').polyfill();
import axios from 'axios'

export function createAsset(text) {
  return {
    type: 'CREATE_ASSET',
    text,
    date: Date.now()
  }
}
export function editAsset(id, text) {
  return {
    type: 'EDIT_ASSET',
    id,
    text,
    date: Date.now()
  };
}
export function deleteAsset(id) {
  return {
    type: 'DELETE_ASSET',
    id
  };
}

function loadAssets(data) {
  return {
    type: 'LOAD_ASSETS',
    data
  }
}

function loadAssetById(data) {
  return {
    type: 'LOAD_ASSET_BY_ID',
    data
  }
}

function errorAction(error) {
  return {
    type: 'ERROR_ASSETS',
    error
  }
}

export function apiMsgAction(msg) {
  return {
    type: 'API_MSG',
    msg
  }
}


export function loadAssetsAsync(data) {
  return function(dispatch) {
    return axios.post('/api/assets', data).then(
      resp => dispatch(loadAssets(resp.data)),
      error => dispatch(errorAction(error))
    );
  };
}

export function loadAssetByMediaIdAsync(data) {
  return function(dispatch) {
    return axios.post('/api/assets/queryById', data).then(
      resp => dispatch(loadAssetById(resp.data)),
      error => dispatch(errorAction(error))
    )
  }
}
